package com.snail.billing;

import java.util.Random;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Looper;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.android.net.HttpApp;
import com.android.net.HttpResult;
import com.android.net.HttpSession;
import com.android.net.OnHttpResultListener;
import com.snail.billing.data.AccountArray;
import com.snail.billing.data.AccountManager;
import com.snail.billing.fragment.view.FloatView;
import com.snail.billing.json.JsonCreateImprestOrder;
import com.snail.billing.json.JsonCreateOrder;
import com.snail.billing.json.JsonLoopMobile;
import com.snail.billing.json.JsonOneKeyRegister;
import com.snail.billing.json.JsonQueryState;
import com.snail.billing.json.JsonRandomRegister;
import com.snail.billing.net.BillingEncode;
import com.snail.billing.session.CreateImprestOrderSession;
import com.snail.billing.session.CreateOrderSession;
import com.snail.billing.session.LoopMobileSession;
import com.snail.billing.session.OneKeyRegisterSession;
import com.snail.billing.session.QueryConfigSession;
import com.snail.billing.session.RandomRegisterSession;

public class BillingLogic {

	private static final String TAG = BillingLogic.class.getName();
	private static final String SEND_REG_SMS = "com.snail.billing.SEND_REG_SMS";

	private Context context;
	private HttpApp httpApp;
	// 一键注册
	private Handler handler;
	private JsonQueryState jsonQueryState;
	private int loopCount;
	
	private static FloatView floatView;

	public BillingLogic(Context context) {
		this.context = context;
	}

	public void oneKeyLogin(final LoginCallback loginCallback) {
		httpApp = new HttpApp(context);
		//
		AccountArray accountArray = AccountManager.getAccountArray();
		if (accountArray.length() == 0) {
			RandomRegisterSession randomRegisterSession = new RandomRegisterSession();
			httpApp.setOnHttpResultListener(new OnHttpResultListener() {

				@Override
				public void onHttpResult(HttpResult httpResult) {
					if (httpResult.isSucceed()) {
						HttpSession httpSession = httpResult.getHttpSession();
						JsonRandomRegister jsonRandomRegister = new JsonRandomRegister((String) httpSession.getResponseData());
						if (jsonRandomRegister.getCode() == 1) {
							String account = jsonRandomRegister.getPassport();
							String pwd = jsonRandomRegister.getPasswd();
							AccountManager.saveRandomAccount(account, pwd);
							if (loginCallback != null) {
								loginCallback.onLoginCallback(account, pwd);
							}
							if (DataCache.getInstance().importParams.loginCallback != null) {
								DataCache.getInstance().importParams.loginCallback.onLoginCallback(account, pwd);
							}
						} else {
							Toast.makeText(context, jsonRandomRegister.getMessage(), Toast.LENGTH_SHORT).show();
						}
					}
				}
			});
			httpApp.request(randomRegisterSession);
		} else {
			String account = accountArray.getAll().get(0).getAccount();
			String pwd = accountArray.getAll().get(0).getPwd();
			if (loginCallback != null) {
				loginCallback.onLoginCallback(account, pwd);
			}
			if (DataCache.getInstance().importParams.loginCallback != null) {
				DataCache.getInstance().importParams.loginCallback.onLoginCallback(account, pwd);
			}
		}
	}

	public void createOrderNo() {
		httpApp = new HttpApp(context);
		//
		if (DataCache.getInstance().importParams.partnerId.equals("007")) {
			final CreateOrderSession createOrderSession = new CreateOrderSession();
			httpApp.setOnHttpResultListener(new OnHttpResultListener() {

				@Override
				public void onHttpResult(HttpResult httpResult) {
					if (httpResult.isSucceed()) {
						HttpSession httpSession = httpResult.getHttpSession();
						JsonCreateOrder jsonCreateOrder = new JsonCreateOrder((String) httpSession.getResponseData());
						if (jsonCreateOrder.getCode() == 1) {
							if (DataCache.getInstance().importParams.paymentOrderCallback != null) {
								DataCache.getInstance().importParams.paymentOrderCallback.onPaymentOrderCallback(jsonCreateOrder.getOrderNo());
							}
						} else {
							Toast.makeText(context, jsonCreateOrder.getMessage(), Toast.LENGTH_SHORT).show();
						}
					}
				}
			});
			httpApp.request(createOrderSession);
		} else {
			final CreateImprestOrderSession createImprestOrderSession = new CreateImprestOrderSession();
			httpApp.setOnHttpResultListener(new OnHttpResultListener() {

				@Override
				public void onHttpResult(HttpResult httpResult) {
					if (httpResult.isSucceed()) {
						HttpSession httpSession = httpResult.getHttpSession();
						JsonCreateImprestOrder jsonCreateImprestOrder = new JsonCreateImprestOrder((String) httpSession.getResponseData());
						if (jsonCreateImprestOrder.getCode() == 1) {
							String orderNo = jsonCreateImprestOrder.getOrderNo();
							if (DataCache.getInstance().importParams.paymentOrderCallback != null) {
								DataCache.getInstance().importParams.paymentOrderCallback.onPaymentOrderCallback(orderNo);
							}
						} else {
							Toast.makeText(context, jsonCreateImprestOrder.getMessage(), Toast.LENGTH_SHORT).show();
						}
					}
				}
			});
			httpApp.request(createImprestOrderSession);
		}
	}

	public void oneKeyRegister() {
		httpApp = new HttpApp(context);
		httpApp.setDialogAutoDismiss(false);
		handler = new Handler(Looper.getMainLooper());
		QueryConfigSession queryConfigSession = new QueryConfigSession();
		httpApp.setOnHttpResultListener(new OnHttpResultListener() {

			@Override
			public void onHttpResult(HttpResult httpResult) {
				if (httpResult.isSucceed()) {
					HttpSession httpSession = httpResult.getHttpSession();
					jsonQueryState = new JsonQueryState((String) httpSession.getResponseData());
					if (jsonQueryState.getCode() == 1) {
						if (jsonQueryState.getData().size() > 0) {
							regSMSReceiver();
							String textToSend = "SWA#" + BillingEncode.enCode(AccountManager.getUUID(), "GBK");
							if (DataCache.getInstance().isSandbox) {
								textToSend = "T" + textToSend;
							}
							Log.w(TAG, "@@@@ SEND_REG_SMS");
							Intent intent = new Intent(SEND_REG_SMS);
							PendingIntent sentIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
							SmsManager smsManager = SmsManager.getDefault();
							smsManager.sendTextMessage(jsonQueryState.getData().get(0).getTargetNumber(), null, textToSend, sentIntent, null);
							handler.postDelayed(sendSMSTimeoutRunnable, 20000);
						} else {
							httpApp.dialogDismiss();
							Toast.makeText(context, "请求短信上行通道失败", Toast.LENGTH_SHORT).show();
						}
					} else {
						httpApp.dialogDismiss();
						Toast.makeText(context, jsonQueryState.getMessage(), Toast.LENGTH_SHORT).show();
					}
				}
			}
		});
		Log.w(TAG, "@@@@ QueryConfig");
		httpApp.request(queryConfigSession);
	}

	private BroadcastReceiver sendStatusReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (SEND_REG_SMS.equals(intent.getAction())) {
				handler.removeCallbacks(sendSMSTimeoutRunnable);
				if (getResultCode() == Activity.RESULT_OK) {
					Log.e("@@@@", "@@@@");
					handler.post(sendSMSOkRunnable);
				} else {
					httpApp.dialogDismiss();
					Toast.makeText(BillingLogic.this.context, "注册短信发送失败", Toast.LENGTH_SHORT).show();
				}
			}
		}
	};

	private Runnable sendSMSTimeoutRunnable = new Runnable() {

		@Override
		public void run() {
			httpApp.dialogDismiss();
			Toast.makeText(context, "注册短信发送超时", Toast.LENGTH_SHORT).show();
		}
	};

	private Runnable sendSMSOkRunnable = new Runnable() {

		@Override
		public void run() {
			unRegSMSReceiver();
			loopCount = 0;
			loopMobile();
		}
	};

	/**
	 * 注册短信发送监听器。
	 */
	private void regSMSReceiver() {
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(SEND_REG_SMS);
		context.registerReceiver(sendStatusReceiver, intentFilter);
	}

	/**
	 * 取消注册短信发送监听器
	 */
	private void unRegSMSReceiver() {
		if (sendStatusReceiver != null) {
			context.unregisterReceiver(sendStatusReceiver);
		}
	}

	private void loopMobile() {
		httpApp.setDialogAutoDismiss(false);
		LoopMobileSession loopMobileSession = new LoopMobileSession();
		httpApp.setOnHttpResultListener(new OnHttpResultListener() {

			@Override
			public void onHttpResult(HttpResult httpResult) {
				if (httpResult.isSucceed()) {
					HttpSession httpSession = httpResult.getHttpSession();
					JsonLoopMobile jsonLoopMobile = new JsonLoopMobile((String) httpSession.getResponseData());
					if (jsonLoopMobile.getCode() == 1) {
						if (TextUtils.isEmpty(jsonLoopMobile.getMobile())) {
							retryLoopMobile();
						} else if (!TextUtils.isEmpty(jsonLoopMobile.getAid())) {
							httpApp.dialogDismiss();
							Toast.makeText(BillingLogic.this.context, "该手机号已注册", Toast.LENGTH_SHORT).show();
						} else if (TextUtils.isEmpty(jsonLoopMobile.getMobileType()) && jsonQueryState.getData().get(0).getReceiveState() != 1) {
							httpApp.dialogDismiss();
							Toast.makeText(BillingLogic.this.context, "无法完成一键注册", Toast.LENGTH_SHORT).show();
						} else {
							requestOneKeyRegister(jsonLoopMobile.getMobile());
						}
					} else {
						retryLoopMobile();
					}
				} else {
					retryLoopMobile();
				}
			}
		});
		Log.w(TAG, "@@@@ LoopMobile " + loopCount);
		httpApp.request(loopMobileSession);
	}

	private void retryLoopMobile() {
		if (loopCount < 8) {
			loopCount++;
			try {
				Thread.sleep(3000);
			} catch (Exception e) {
			}
			loopMobile();
		} else {
			httpApp.dialogDismiss();
			Toast.makeText(BillingLogic.this.context, "无法完成一键注册", Toast.LENGTH_SHORT).show();
		}
	}

	private void requestOneKeyRegister(String userName) {
		final String pwd = String.valueOf(randowNumberPwd(8));
		StringBuilder builder = new StringBuilder();
		builder.append(getMeidaID()).append("|").append(getAppVersion()).append("|").append(AccountManager.getUUID()).append("|").append(getProviderName());
		final String fromValue = builder.toString();
		OneKeyRegisterSession oneKeyRegisterSession = new OneKeyRegisterSession(userName, pwd, fromValue);
		httpApp.setOnHttpResultListener(new OnHttpResultListener() {

			@Override
			public void onHttpResult(HttpResult httpResult) {
				if (httpResult.isSucceed()) {
					HttpSession httpSession = httpResult.getHttpSession();
					JsonOneKeyRegister jsonOneKeyRegister = new JsonOneKeyRegister((String) httpSession.getResponseData());
					if (jsonOneKeyRegister.getCode() == 1) {
						String account = jsonOneKeyRegister.getAccount();
						AccountManager.saveAccount(account, pwd);
						if (DataCache.getInstance().importParams.loginCallback != null) {
							DataCache.getInstance().importParams.loginCallback.onLoginCallback(account, pwd);
						}
					} else {
						Toast.makeText(BillingLogic.this.context, jsonOneKeyRegister.getMessage(), Toast.LENGTH_SHORT).show();
					}
				}
			}
		});
		Log.w(TAG, "@@@@ OneKeyRegisterSession ");
		httpApp.request(oneKeyRegisterSession);
	}

	private int randowNumberPwd(int num) {
		Random random = new Random();
		int number = random.nextInt((int) Math.pow(10, num));
		if (number < (int) Math.pow(10, num - 1)) {
			number += (random.nextInt(9) + 1) * Math.pow(10, num - 1);
		}
		return number;
	}

	private String getMeidaID() {
		String defaultID = "0";
		try {
			ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
			if (appInfo.metaData != null) {
				String mediaID = appInfo.metaData.getInt("media_id", Integer.parseInt(defaultID)) + "";
				if (!TextUtils.isEmpty(mediaID)) {
					return mediaID;
				}
			}
		} catch (Exception e) {
		}
		return defaultID;

	}

	private String getAppVersion() {
		try {
			return context.getPackageManager().getPackageInfo(context.getPackageName(), Context.MODE_PRIVATE).versionName;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	private String getProviderName() {
		TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		String providerId = telephonyManager.getSubscriberId();
		if (!TextUtils.isEmpty(providerId)) {
			if (providerId.startsWith("46000") || providerId.startsWith("46002")) {
				// return "中国移动";
				return "2";
			} else if (providerId.startsWith("46001")) {
				// return "中国联通";
				return "1";
			} else if (providerId.startsWith("46003")) {
				// return "中国电信";
				return "3";
			}
		}
		return "";
	}
	
	public void showUserCenterFloatView() {
		floatView = new FloatView(context);
		floatView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(context, Billing.class);
				context.startActivity(intent);
			}
		});
		floatView.show();
	}
	

	public void dismissUserCenterFloatView() {
		floatView.dismiss();
	}

}
